//
//  DetectionViewController.m
//  INMOTION
//
//  Created by Kyle on 14-4-11.
//  Copyright (c) 2014年 Inmotion. All rights reserved.
/*
 故障检测：
 */

#import "DetectionViewController.h"
#import "UIViewController+NavButton.h"
#import "DetectionCell.h"
#import "DetectionHeaderView.h"
#import "DetectionModel.h"
#import "IMTCarLogModel.h"
#import "CarModel.h"
#import "IMFunction.h"
#import "IMTConfig.h"
#import "NSObject+HUD.h"
#import "KSLanguageManager.h"
#import "IMTCANManager.h"
#import "IMTCANMessageFactory.h"
#import "UIImage+Category.h"
#import "AppTypeTool.h"

// L9实时故障
#import "L9DetectionModel.h"

typedef NS_ENUM(NSInteger,DetectionState){
    DetectionStateNormal = 0,   // 普通
    DetectionStateChecking,     // 正在进行故障检测
    DetectionStateCheckOver,    // 故障检测结束
    DetectionStateReading,      // 正在读取日志
    DetectionStateUploading,    // 正在上传日志
};

@interface DetectionViewController () <UITableViewDataSource, UITableViewDelegate>

typedef void(^GetStateBlock)(void);

@property(nonatomic, strong) NSMutableArray *nameItems;
@property(nonatomic, strong) NSMutableArray *photoItems;
@property(nonatomic, weak) IBOutlet UIView *headerBackgroundView;
@property(nonatomic, strong) DetectionHeaderView *headerView;
@property(weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, strong) DetectionModel *detectionModel;
@property(nonatomic, strong) IMTCarLogModel *logModel;
@property(nonatomic, assign) NSInteger receiveIndex;
@property(nonatomic, assign) NSInteger remainingSize;
@property(weak, nonatomic) IBOutlet NSLayoutConstraint *tabviewTop;
@property(weak, nonatomic) IBOutlet NSLayoutConstraint *headViewHeight;

@property(nonatomic, assign) u_int32_t currentIndex; // 获取日志数据的下标
@property(nonatomic, strong) NSMutableArray *detectionAry;
@property(nonatomic, strong) NSString *errorCode;

@property (nonatomic, strong) L9DetectionModel *l9_detectionModel;

@property(nonatomic, assign) BOOL shouldStop;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, assign) DetectionState detectionState;

@end

@implementation DetectionViewController

-(NSMutableArray *)detectionAry {
    if (!_detectionAry) {
        _detectionAry = [NSMutableArray arrayWithCapacity:1];
    }
    return _detectionAry;
}

- (IMTCarLogModel *)logModel {
    if (!_logModel) {
        _logModel = [[IMTCarLogModel alloc] init];
    }
    return _logModel;
}

- (DetectionHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[[NSBundle mainBundle] loadNibNamed:@"DetectionHeaderView" owner:self options:nil] lastObject];
        _headerView.frame = _headerBackgroundView.bounds;
        [_headerBackgroundView addSubview:_headerView];
    }
    return _headerView;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)stopTimmer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)dealloc {
    [self stopTimmer];
    [self dismissHUD];
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self dismissHUD];
    [self stopTimmer];
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

/// 返回按钮
- (void)closeButtonPressed {
    
    if (self.detectionState == DetectionStateChecking) { // 正在进行故障检测
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:IMTNewCarLocalizedString(@"prompt_sure_to_quit_diagnose") preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:nil];
        UIAlertAction *other = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"activity_diagnose_stop") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self stopTimmer];
            [self dismissHUD];
            if (self.navigationController.viewControllers.count == 1) {
                [self dismissViewControllerAnimated:true completion:nil];
            } else {
                [self.navigationController popViewControllerAnimated:true];
            }
        }];
        [vc addAction:cancle];
        [vc addAction:other];
        [self presentViewController:vc animated:YES completion:nil];
    } else {
        [self stopTimmer];
        [self dismissHUD];
        if (self.navigationController.viewControllers.count == 1) {
            [self dismissViewControllerAnimated:true completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = IMTNewCarLocalizedString(@"fragment_car_settings_diagnose");
    self.tableView.backgroundColor = kIMTDefaultBackgroundColor;
    self.view.backgroundColor = kIMTDefaultBackgroundColor;
    self.headerView.backgroundColor = kIMTDefaultBackgroundColor;
    self.headerView.detectionIcon.image = [[UIImage imageNamed:@"FaultDetect.png"] imgWithTintColor:[AppTypeTool getThemeColor]];
    self.headerView.progressLabel.textColor = [AppTypeTool getThemeColor];
    self.headerView.percentNotation.textColor = [AppTypeTool getThemeColor];

    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back_white"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(closeButtonPressed)];
    self.navigationItem.leftBarButtonItem = left;

    [self setExtraCellLineHidden:self.tableView];
    self.detectionModel = [[DetectionModel alloc] init];
    self.detectionState = DetectionStateNormal;
    self.shouldStop = NO;
    
    self.nameItems = [self.detectionModel loadErrorNameItemWithCarType:self.carModel.carType];
    self.photoItems = [self.detectionModel loadErrorImageItemWithCarType:self.carModel.carType];
    
    [self.headerView.startButton addTarget:self action:@selector(startButtonPressed) forControlEvents:UIControlEventTouchUpInside];

    self.headerView.startButton.layer.borderColor = IMTColor(230, 230, 230).CGColor;
    self.headerView.startButton.layer.borderWidth = 2.0f;
    self.headerView.startButton.layer.cornerRadius = 40.0f;
    self.headerView.startButton.layer.masksToBounds = YES;
    self.headerView.startLabel.text = IMTNewCarLocalizedString(@"activity_diagnose_start");
    self.headerView.tipsLabel.text = IMTNewCarLocalizedString(@"activity_diagnose_description");
    [self.view addSubview:self.headerView];
    
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        [self startButtonPressed];
    }
}

#pragma mark - 获取R0的错误代码
/// 开始检测按钮
- (void)startButtonPressed {
    if ([self.headerView.startLabel.text isEqualToString:IMTNewCarLocalizedString(@"activity_diagnose_start")]) {
        [self checkDeviceError];
    }else {
        [self stopDetection];
    }
}

//停止检测
- (void)stopDetection {
    self.detectionState = DetectionStateNormal;
    self.errorCode = nil;
    [self.detectionModel.errorCategories removeAllObjects];
    [self.l9_detectionModel.errorCategories removeAllObjects];

    // 重置headerview
    [self resetHeadView];
}

#pragma mark - 错误代码
- (void)checkDeviceError {
    if (![KSBLEManager sharedManager].connected) {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_bt_is_not_connected")];
        return;
    }
    self.headerView.startLabel.text = IMTNewCarLocalizedString(@"activity_diagnose_stop");
    self.headerView.progressLabel.hidden = NO;
    self.headerView.progressLabel.text = @"0";
    self.headerView.percentNotation.hidden = NO;
    self.headerView.detectionIcon.hidden = YES;
    [self.headerView drawArcLine];
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        [self.headerView drawLineAnimationWithduration:1];
    }else {
        [self.headerView drawLineAnimationWithduration:10];
    }
    self.detectionState = DetectionStateChecking;
    self.tableView.userInteractionEnabled = NO;
    [self.tableView reloadData];
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    CGFloat timeInterval = 0.1;
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        timeInterval = 0.01;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(timeIncrease) userInfo:nil repeats:YES];
    
    if (IMTCarSeriesLorin(self.carModel.carType)) { // l9的错误码获取
        self.l9_detectionModel = [[L9DetectionModel alloc] init];
        [self getErrorForL9];
    }
}

/// 获取错误数据 -- l9错误码
- (void)getErrorForL9 {
    WS(weakSelf)
    [self.carModel.l9_CarModel getDataWithCmdType:(L9_CarModelCmdTypeRealTimeError) isRepeat:YES compleBlock:^(NSError *error, NSData *responseData) {
        if (!error) {
            uint16_t result;
            [responseData getBytes:&result range:NSMakeRange(0, responseData.length)];
            [weakSelf.l9_detectionModel loadL9ErrorCategoryAndMessageWithData:self.carModel.l9_CarModel.errorValues];
        }else {
            [weakSelf getDeviceErrorFail];
        }
    }];
}

// 获取错误码失败
- (void)getDeviceErrorFail {
    [self showErrorHUDWithText:IMTNewCarLocalizedString(@"activity_diagnose_failed")];
    [self resetHeadView];
    [self stopTimmer];
    self.detectionState = DetectionStateNormal;
}

- (void)timeIncrease {
    int time = self.headerView.progressLabel.text.intValue;
    self.headerView.progressLabel.text = [NSString stringWithFormat:@"%d", ++time];
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        if (time%10 == 0) {
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:(time/10) % self.nameItems.count inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }else {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:time % self.nameItems.count inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    }
    if (time >= 100) {
        
        [self resetHeadView];
        if (IMTCarSeriesLorin(self.carModel.carType)) {
            [self showResultWithResult:self.l9_detectionModel.errorMessage isCheck:NO];
        }else {
            if (self.detectionModel.errorCategories.count == 0) {
                [self showResultWithResult:@"prompt_diagnose_ok" isCheck:NO];
            }else {
                [self showResultWithResult:self.detectionModel.errorMessage isCheck:NO];
            }
        }

        self.detectionState = DetectionStateCheckOver;
        [self.tableView reloadData];
        
    }
}

- (void)showResultWithResult:(NSString *)result isCheck:(BOOL)isCheck {
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:result preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_btn_i_see") style:(UIAlertActionStyleCancel) handler:nil];
    [vc addAction:ok];
    [self presentViewController:vc animated:YES completion:nil];
}

// 重置header
- (void)resetHeadView {
    self.headerView.startLabel.text = IMTNewCarLocalizedString(@"activity_diagnose_start");
    self.headerView.progressLabel.hidden = YES;
    self.headerView.progressLabel.text = @"0";
    self.headerView.percentNotation.hidden = YES;
    self.headerView.detectionIcon.hidden = NO;
    self.tableView.userInteractionEnabled = YES;
    [self stopTimmer];
    [self.headerView resetArcLine];
    self.headerView.tipsLabel.text = IMTNewCarLocalizedString(@"activity_diagnose_description");
    [self.tableView reloadData];
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.nameItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        DetectionCell *cell = (DetectionCell *) [[[NSBundle mainBundle] loadNibNamed:@"DetectionCell" owner:self options:nil] lastObject];
        
        cell.accessoryName.text = [self.nameItems objectAtIndex:indexPath.row];
        cell.accessoryImage.image = [UIImage imageNamed:[self.photoItems objectAtIndex:indexPath.row]];
        
        if (self.detectionState == DetectionStateCheckOver) {
            if (IMTCarSeriesLorin(self.carModel.carType)) {
                if ([self.l9_detectionModel.errorCategories containsObject:@(indexPath.row)]) {
                    cell.resultImage.image = [UIImage imageNamed:@"Fault"];
                }else {
                    cell.resultImage.image = [UIImage imageNamed:@"dialog_ok"];
                }
            }
        }else {
            cell.resultImage.image = nil;
            }
        return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 20;
}

#pragma mark - TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
